<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容" v-model="queryInfo.query"
          clearable
          @click="getUserList"
          >
            <el-button slot="append" icon="el-icon-search"
             @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary"
         @click="dialogVisible = true"
          >添加用户</el-button>
        </el-col>
      </el-row>
      <el-table :data="userList" style="width: 100%" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态" prop="mg_state">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChanged(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column label="操作" width="180px" >
          <template  slot-scope="scope">
            <!-- 修改 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
             
              @click="showEditDialog(scope.row.id)"
           
            
            ></el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
            ></el-button>
            <!-- 分配角色 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

<!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="2"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

<!-- 添加用户对话框 -->
    <el-dialog
  title="添加用户"
  :visible.sync="dialogVisible"
  width="30%"
 @close="resetLoginForm"
  >
  <el-form ref="addFormRef" :model="addForm" :rules="rules" label-width="100px" class="loginForm">
<!-- 用户名 -->
        <el-form-item prop="username" label="用户名">
          <el-input
            v-model="addForm.username"
            
          ></el-input>
        </el-form-item>
<!-- 密码 -->
        <el-form-item prop="password" label="密码">
          <el-input v-model="addForm.password"  type="password"></el-input>
        </el-form-item>

 <el-form-item prop="mobile" label="手机号">
          <el-input v-model="addForm.mobile"  ></el-input>
        </el-form-item>


 <el-form-item prop="email" label="邮箱">
          <el-input v-model="addForm.email"  ></el-input>
        </el-form-item>



      </el-form>

  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false"
     
    >取 消</el-button>
    <el-button type="primary"  
    @click="addUser" >确 定</el-button>
  </span>
</el-dialog>

<!-- 修改用户对话框 -->
<el-dialog
  title="修改用户"
  :visible.sync="editDialogVisible"
  width="30%"
  >
 <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
    <el-form-item label="用户名">
        <el-input v-model="editForm.username" disabled></el-input>
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
        <el-input v-model="editForm.email"></el-input>
    </el-form-item>
    <el-form-item label="电话" prop="mobile">
        <el-input v-model="editForm.mobile"></el-input>
    </el-form-item>
</el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editDialogVisible = false">确 定</el-button>
  </span>
</el-dialog>

  </div>
</template>

  

<script>
export default {

  data() {
  //验证邮箱的规则
  var checkEmail = (rule, value, cb) => {
    const regEmail = /^\w+@\w+(\.\w+)+$/
    if (regEmail.test(value)) {
      return cb()
    }
    //返回一个错误提示
    cb(new Error('请输入合法的邮箱'))
  }
  //验证手机号码的规则
  var checkMobile = (rule, value, cb) => {
    const regMobile = /^1[34578]\d{9}$/
    if (regMobile.test(value)) {
      return cb()
    }
    //返回一个错误提示
    cb(new Error('请输入合法的手机号码'))
  }
    return {

         dialogVisible: false,

 addForm: {
        username: "",
        password: "",
        mobile:"",
        email:"",

 },

 
 
          rules:{
        //验证用户名是否合法
        username:[
           { required: true, message: '请输入登录名称', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        //验证用户密码是否合法
        password:[
           { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 10, message: '长度在 6 到 10 个字符', trigger: 'blur' }
        ],
          mobile:[
           { required: true, message: '请输入手机号', trigger: 'blur' },
            { validator:checkMobile, trigger: 'blur' }
        ],
          email:[
           { required: true, message: '请输入邮箱', trigger: 'blur' },
            { validator:checkEmail,trigger: 'blur' }
        ]
      },
      //获取查询用户信息
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2,
      },
      //保存请求回来的用户列表数据
      userList: [],
      total: 0,
      editForm:{},
      editFormRules:{},

    //   控制修改用户对话框的显示与隐藏
      editDialogVisible:false,

      editForm:{},
      editFormRules:{
           email:[
           { required: true, message: '请输入邮箱', trigger: 'blur' },
            { validator:checkEmail,trigger: 'blur' }
        ],
          mobile:[
           { required: true, message: '请输入手机号', trigger: 'blur' },
            { validator:checkMobile, trigger: 'blur' }
        ],
      }
    }
  },
  
  created() {
    this.getUserList()
  },
  methods: {
      resetLoginForm(){
 this.$refs.addFormRef.resetFields()
},
    async getUserList() {
      //发送请求获取用户列表数据
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo,
      })
      console.log(res)
      //如果返回状态为异常状态则报错并返回
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      //如果返回状态正常，将请求的数据保存在data中
      this.userList = res.data.users
      this.total = res.data.total
    },

    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize

      this.getUserList()
    },

    handleCurrentChange(current) {
      this.queryInfo.pagenum = current

      this.getUserList()
    },

    async userStateChanged(usereinfo) {
      // console.log(usereinfo);

      const { data: res } = await this.$http.put(
        `users/${usereinfo.id}/state/${usereinfo.mg_state}`
      )
      if (res.meta.status != 200) {
        usereinfo.mg_state = !usereinfo.mg_state
        return this.$message.error('用户更新失败')
      }
      this.$message.success('用户更新成功')
    },
    

addUser(){
    this.$refs.addFormRef.validate(async valid=>{
        if(!valid) return
        const {data:res}=await this.$http.post("users",this.addForm);
        if(res.meta.status!=201)return this.$message.error(res.meta.msg);
        this.$message.success("添加成功");
        this.dialogVisible=false;
        this.getUserList()
    })
},
// 显示用户信息
// showEditDialog(id){
//     this.editDialogVisible=true
//     console.log(id);
// }
async showEditDialog(id){
   const {data:res}=await this.$http.get(`users/${id}`)
   
   if(res.meta.status !=200) return this.$message.error("获取用户信息失败");
    this.editForm = res.data
    //显示弹出窗
    this.editDialogVisible = true

}
  },
}
</script>

<style lang="" scoped>
</style>